package com.zzj.ecology.framework.interceptor;

import com.zzj.ecology.common.config.Audience;
import com.zzj.ecology.common.utils.JWTUtils;
import com.zzj.ecology.common.utils.StringUtils;
import com.zzj.ecology.framework.exception.TgfException;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName AuthorizationInterceptor
 * @Description TODO
 * @Author zhijun zeng at 0:00 2020/5/30
 * @Version 1.0
 **/
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // token
        String token = request.getHeader(JWTUtils.TOKEN_KEY);
        if (StringUtils.isEmpty(token)) {
            token = request.getParameter(JWTUtils.TOKEN_KEY);
        }

        if (StringUtils.isBlank(token)) {
            throw new TgfException( JWTUtils.TOKEN_KEY + " 不能为空， 需要重新授权登录 ", HttpStatus.SC_UNAUTHORIZED);
        }

        if (JWTUtils.isTokenExpired(token)) {
            throw new TgfException( JWTUtils.TOKEN_KEY + " 已经过期， 需要重新授权登录 ", HttpStatus.SC_UNAUTHORIZED);
        }


        return super.preHandle(request, response, handler);
    }
}
